;; Non-robust linear algebra functions
;; Copyright (C) 2025  Rocks Mazama
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

(ns mazama.linalg.determinant
  (:require
   [mazama.linalg.r-e-f :as r-e-f]))

(defn determinant-2
  "Compute the determinant of a 2x2 matrix."
  [a b c d]
  (- (* a d) (* b c)))

(defn determinant-3
  "Compute the determinant of a 3x3 matrix."
  [a b c d e f g h i]
  (+ (* a (determinant-2 e f h i))
     (- (* b (determinant-2 d f g i)))
     (* c (determinant-2 d e g h))))

(defn determinant-4
  "Compute the determinant of a 4x4 matrix."
  [a b c d e f g h i j k l m n o p]
  (+ (* a (determinant-3 f g h j k l n o p))
     (- (* b (determinant-3 e g h i k l m o p)))
     (* c (determinant-3 e f h i j l m n p))
     (- (* d (determinant-3 e f g i j k m n o)))))

(defn- determinant-n
  "Compute the determinant of an nxn matrix."
  [m]
  (let [{:keys [pivot-column-indexes pivot-rows zero-rows ero-scale]} (r-e-f/r-e-f m)]
    (if (seq zero-rows)
      0
      (reduce * ero-scale (map nth pivot-rows pivot-column-indexes)))))

(defn determinant
  "Compute the determinant of a square matrix."
  [{:keys [ncols data] :as m}]
  (when (== (* ncols ncols) (count data)) ; when square
    (case ncols
      1 (first data)
      2 (let [[a b c d] data] (determinant-2 a b c d))
      3 (let [[a b c d e f g h i] data] (determinant-3 a b c d e f g h i))
      4 (let [[a b c d e f g h i j k l m n o p] data]
          (determinant-4 a b c d e f g h i j k l m n o p))
      (determinant-n m))))
